const express = require('express')
const UserModel = require('../../models/UserModel')
const md5 = require('md5')

const router = express.Router()

// 注册
router.get('/reg', (req, res, next) => {
    res.render('auth/reg')
})

router.post('/reg', (req, res, next) => {
    console.log(req.body);
    UserModel.create({
       ...req.body,
       password: md5(req.body.password) 
    }).then(data => {
        console.log(data);
        res.render('success', {msg: '注册成功', url: '/login'})
    }).catch(err => {
        res.status(500).send('注册失败')
    })
})

// 登录页
router.get('/login', (req, res, next) => {
    res.render('auth/login')
})


router.post('/login', (req, res, next) => {
    const {username, password} = req.body
    UserModel.findOne({username: username, password: md5(password)}).then(data => {
        console.log(data);
        if (!data) {
           return res.status(500).send('账号或密码错误')
        }
        // console.log(req.session);
        // 登陆成功，写入session
        req.session.username = data.username
        req.session._id = data._id
    
        res.render('success', {msg: '登陆成功', url: '/account'})
    }).catch(err => {
        res.status(500).send('登陆失败')
    })
})

// 退出登录
router.post('/logout', (req, res, next) => {
    req.session.destroy(() => {
        res.render('success', {msg: '推出成功', url: '/login'})
    })
})



module.exports = router